package com.cipe.cmrs.util;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.propertyeditors.CustomCollectionEditor;

import com.cipe.cmrs.bean.LinkRoleEntryBean;

public class LinkBeanCollectionEditor  extends CustomCollectionEditor {

	protected Logger logger = LoggerFactory.getLogger(LinkBeanCollectionEditor.class); 

//	private final Map<String, RoleEntryBean> linkCache;

    @SuppressWarnings("rawtypes")
	public LinkBeanCollectionEditor(Class collectionType) {
		super(collectionType);
//		linkCache = new HashMap<String, RoleEntryBean>();
	}

	@Override
    protected Object convertElement(Object element) {		
		try {
			LinkRoleEntryBean roleEntryBean = null;
	        if (element instanceof LinkRoleEntryBean) {
	        	roleEntryBean = (LinkRoleEntryBean) element;
	        } else if (element instanceof String) {
	            //From the JSP 'element' will be a String
	        	if (!StringUtils.isBlank(element.toString())) {
	        		String[] elementIdStr = ((String) element).split("-");
	        		String linkIdStr = elementIdStr[1];
	        		String roleIdStr = elementIdStr[0];
 
	        		roleEntryBean = new LinkRoleEntryBean(Integer.valueOf(roleIdStr), Integer.valueOf(linkIdStr), Boolean.TRUE);
	        	}
	        }
	        return roleEntryBean;
        } catch (Exception ex) {
			logger.debug("Value could not be converted: " + (String) element);
			throw new IllegalArgumentException("Value could not be converted: " + (String) element);
        }
    }

}
